package linter.controller.user;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import linter.POJO.DO.User;
import linter.POJO.DTO.UserDTO;
import linter.POJO.UtilDTO.SmsDTo;
import linter.custom.Constant;
import linter.custom.ResultVO;
import linter.mapper.UserMapper;
import linter.service.UserService;
import linter.utils.JwtUtils;
import linter.utils.MailUtils;
import linter.utils.RedisUtils;
import linter.utils.SmsUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

import static linter.custom.CustomResultType.USER_NOT_EXIST;

/**
 * @author 北煜
 *
 * TODO：用户角色的变更，电话和邮箱的验证。
 */
@Api(tags = "用户主体控制器")
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Resource
    UserService userService;
    @Resource
    UserMapper userMapper;

    @GetMapping("/show/getUserByUsername/{username}")
    @ApiOperation("根据用户名查找用户")
    public ResultVO<UserDTO> getUserByUsername(@PathVariable String username) {
        UserDTO userDTO = userService.getUserByUsername(username);
        return ResultVO.success(userDTO);
    }

    @PostMapping("/all")
    @ApiOperation("查询所有用户并且可以通过用户名来查询")
    public ResultVO<PageInfo<User>> page(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                         @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                         @RequestParam(value = "username", defaultValue = "") String username){
        List<User> list = userService.selectall(pageNum,pageSize,username);
        return ResultVO.success(new PageInfo<>(list));
    }

    @PostMapping("/login")
    @ApiOperation("登录")
    public ResultVO<?> login(@RequestBody User user){
        String username = user.getUsername();
        String pwd = user.getPassword();
        String result =userService.checkLogin(username,pwd);
        // 三种返回：1.用户不存在 2.密码错误 3.登录成功返回token
        if(result.length() > 20){
            return ResultVO.success("登录成功",result);
        }
        return ResultVO.error(result);
    }

    @PostMapping("/getUserRole")
    @ApiOperation("获取用户角色")
    public ResultVO<?> getUserRole(){
        String username = JwtUtils.getUserName((String) SecurityUtils.getSubject().getPrincipal());
        System.out.println(username);
        if (username != null){
            return ResultVO.success(userService.getUserRole(username));
        }
        return ResultVO.error(USER_NOT_EXIST);
    }

    @PostMapping("/register")
    @ApiOperation("注册")
    public ResultVO<String> register(@RequestBody User user) {
        String username = user.getUsername();
        String pwd = user.getPassword();
        UserDTO checkUser = userService.getUserByUsername(username);
        if (checkUser != null){
            return ResultVO.error("用户名已存在");
        }
        Long result = userService.register(username,pwd);
        if(result == 5L){
            return ResultVO.success("注册成功");
        }else {
            if (result == 0L) {
                return ResultVO.error("注册失败,请重试");
            } else if (result == -1L) {
                log.error("注册失败,数据库回滚错误，检查用户表");
                return ResultVO.error("注册失败,系统错误");
            }
        }
        return ResultVO.error("注册失败");
    }

    @DeleteMapping("/outLogin")
    @ApiOperation("退出登录")
    public ResultVO<?> outLogin() {
        String username = JwtUtils.getUserName((String) SecurityUtils.getSubject().getPrincipal());
        System.out.println(username);
        if (username != null){
            if (RedisUtils.hasKey(username)){
                RedisUtils.del(username);
            }
            return ResultVO.success("成功退出登录");
        }
        return ResultVO.error("退出登录异常");
    }

    @DeleteMapping("/closeUser")
    @ApiOperation("注销账户")
    public ResultVO<?> closeUser() {
        String username = JwtUtils.getUserName((String) SecurityUtils.getSubject().getPrincipal());
        System.out.println(username);
        if (username != null){
            Long id = userService.getIdByUsername(username);
            boolean successOrError = userService.removeAllById(id);
            if (successOrError){
                return ResultVO.success("注销成功");
            }else {
                return ResultVO.error("注销失败");
            }
        }
        return ResultVO.error("注销异常，是否登录");
    }
    @PostMapping("/sendLogin")
    @ApiOperation("发送登录验证码")
    public ResultVO<?> sendLogin(@RequestBody SmsDTo sms){
        if (userService.selectPh(sms.getPhoneNumber()) == null){
            return ResultVO.error("用户未注册");
        }else{
            String ma =  SmsUtil.sendLogin(sms.getPhoneNumber(), Constant.loginId);
            RedisUtils.put(sms.getPhoneNumber(),ma,180);
            return ResultVO.success("发送成功");
        }

}
    @PostMapping("/smsLogin")
    @ApiOperation("短信登录校验")
    public ResultVO<?> smsLogin(@RequestBody  SmsDTo sms){
        Object ma = RedisUtils.get(sms.getPhoneNumber());
        if (ma == null){
            return ResultVO.error("验证码错误");
        }
        String maString = ma.toString();
        if (maString.equals(sms.getCode())){
            String result = userService.loginPh(sms.getPhoneNumber());
            return ResultVO.success(result);
        }else{
            return ResultVO.error("验证码错误");
        }
    }
    @Autowired
    private MailUtils mailUtils;
    @PostMapping("/sendQQ")
    public ResultVO<?> sendQQ(@RequestBody User user){
        Random random = new Random();
        int randomNumber = random.nextInt(9000) + 1000;
        String randomNumberAsString = String.valueOf(randomNumber);
        mailUtils.sendMail(user.getEmail(),"您的验证码为"+randomNumberAsString,"linter登录验证码");
        return null;
    }




}
